package com.example.sxmall.controller;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.sxmall.common.dto.MailDto;
import com.example.sxmall.common.dto.PassDto;
import com.example.sxmall.common.lang.Result;
import com.example.sxmall.dao.pojo.Admins;
import com.example.sxmall.dao.pojo.AdminsPermis;
import com.example.sxmall.dao.pojo.Permission;
import com.example.sxmall.service.AdminsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zhang
 * @since 2022-03-22
 */
@RestController
@RequestMapping("/admins")
public class AdminsController extends BaseController {
    @Autowired
    BCryptPasswordEncoder passwordEncoder;
    @Autowired
    AdminsService adminsService;

    @GetMapping("/info/{id}")
    @PreAuthorize("hasAuthority('sys:admins:list')")
    public Result info(@PathVariable("aid") Integer aid) {

        Admins admins = adminsService.getById(aid);
        //判断是否为空
        Assert.notNull(admins, "找不到该管理员");

        List<Permission> permissions = permissionService.listPermByAdminsId(aid);

        admins.setPermissions(permissions);
        return Result.succ(admins);
    }

    @GetMapping("/list")
    @PreAuthorize("hasAuthority('sys:admins:list')")
    public Result list(String account) {

        Page<Admins> pageData = adminsService.page(getPage(), new QueryWrapper<Admins>()
                .like(StrUtil.isNotBlank(account), "acount", account));

        pageData.getRecords().forEach(admins -> {

            admins.setPermissions(permissionService.listPermByAdminsId(admins.getAid()));
        });

        return Result.succ(pageData);
    }

    @PostMapping("/save")
    @PreAuthorize("hasAuthority('sys:admins:save')")
    public Result save(@Validated @RequestBody Admins admins,PassDto passDto) {
        /*String psd= passwordEncoder.encode(password);*/
        admins.setApwd(passwordEncoder.encode(passDto.getPassword()));

        adminsService.save(admins);
        return Result.succ(admins);
    }

    @PostMapping("/update")
    @PreAuthorize("hasAuthority('sys:admins:update')")
    public Result update(@Validated @RequestBody Admins admins) {
        adminsService.updateById(admins);
        return Result.succ(admins);
    }

    @Transactional
    @PostMapping("/delete")
    @PreAuthorize("hasAuthority('sys:admins:delete')")
    public Result delete(@RequestBody Integer[] aids) {

        adminsService.removeByIds(Arrays.asList(aids));
        adminsPermisService.remove(new QueryWrapper<AdminsPermis>().in("aid", aids));

        return Result.succ("");
    }

    /*分配角色*/
    @Transactional
    @PostMapping("/perm/{adminsId}")
    @PreAuthorize("hasAuthority('sys:admins:perm')")
    public Result rolePerm(@PathVariable("adminsId") Integer adminsId, @RequestBody Integer[] permIds) {

        List<AdminsPermis> adminsPermiss = new ArrayList<>();

        Arrays.stream(permIds).forEach(r -> {
            AdminsPermis adminsPermis = new AdminsPermis();
            adminsPermis.setPerid(r);
            adminsPermis.setAid(adminsId);

            adminsPermiss.add(adminsPermis);
        });

        adminsPermisService.remove(new QueryWrapper<AdminsPermis>().eq("aid", adminsId));
        adminsPermisService.saveBatch(adminsPermiss);

        // 删除缓存
        Admins admins = adminsService.getById(adminsId);
        adminsService.clearAdminAuthorityInfo(admins.getAcount());

        return Result.succ("");
    }

    @PostMapping("/repass")
    @PreAuthorize("hasAuthority('sys:admins:repass')")
    public Result repass(@RequestBody Integer adminsId,PassDto passDto) {

        Admins admins = adminsService.getById(adminsId);

        admins.setApwd(passwordEncoder.encode(passDto.getPassword()));

        adminsService.updateById(admins);
        return Result.succ("");
    }

    //修改密码
    @PostMapping("/updatePass")
    public Result updatePass(@Validated @RequestBody PassDto passDto, Principal principal) {

        Admins admins = adminsService.getByAdminsName(principal.getName());

        boolean matches = passwordEncoder.matches(passDto.getCurrentPass(), admins.getApwd());
        if (!matches) {
            return Result.fail("旧密码不正确");
        }

        admins.setApwd(passwordEncoder.encode(passDto.getPassword()));

        adminsService.updateById(admins);
        return Result.succ("");
    }



    /*发送邮件*/
    @PostMapping("/sendMail")
    public Result sendMail(@Validated @RequestBody MailDto mailDto){
        adminsService.sendMail(mailDto);
        return Result.succ("");
    }

}
